package com.twu.biblioteca.service;

import com.twu.biblioteca.exceptions.BookDoesntBelongToLibraryException;
import com.twu.biblioteca.model.Book;
import com.twu.biblioteca.model.Library;
import com.twu.biblioteca.model.LibraryService;
import com.twu.biblioteca.model.ServiceResult;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Created by davecroman on 12/09/2014.
 */
public class ReturnBookService extends LibraryService {

    private static String name = "Return Book";

    public ReturnBookService(Library library){
        super(library);
    }

    @Override
    public ServiceResult performService() {
        System.out.print("Enter book id to return: ");
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));

        try {
            String input = bufferRead.readLine();
            Integer bookId = Integer.parseInt(input);
            return performService(bookId);
        } catch (Exception e) {
            return new ServiceResult("Return Failed: Input Invalid");
        }
    }

    @Override
    public String getName() {
        return name;
    }

    public ServiceResult performService(Integer bookId) {
        final Book book = library.getAllBooks().get(bookId);

        try {
            library.returnBook(book);
        } catch (BookDoesntBelongToLibraryException e) {
            return new ServiceResult("That is not a valid book to return.");
        }

        return new ServiceResult("Thank you for returning the book.");
    }
}
